#pragma once
#include <map>
#include <list>
#include <vector>
#include <string>
#include "Object.h"
#include "EventLoop.h"
#include "Server.h"
#include "Worker.h"
#include "Atomic.h"

#define LockAcceptMutex(lock, val) atomic_cmp_set(lock, 0, val)
#define UnLockAcceptMutex(lock, val) atomic_cmp_set(lock, val, 0)

NS_BEGIN

typedef struct{
	atomic_t	lock;
	int			clients;
	int			workerClients[0];
}GlobalData;

typedef struct{
	int type;
	std::string host;
	short port;
	short weight;
}BackendOption;

typedef std::vector<BackendOption> BackendServer;
typedef std::map<std::string, std::string> FastcgiParams;

class Master:
	public Object
{
private:
	Master();
	~Master();
public:
	void 			start(int argc, char **argv);
	static Master*	getInstance();
	void			setProcTitle(const char *title);
private:
	void			daemonize();
	bool			createGlobals();
	void			releaseGlobals();
	void 			setupSignal();
	bool			loadConfig();
	static void 	procSignal(int sig);
	bool			addBackendServer(const char *str, int weight);
	void			initProcTitle();
public:
	int				nArgc;
	char**			pArgv;
	Server*			pServer;
	Worker**		pWorkers;
	GlobalData*		pGlobals;
	std::string		sConfigFile;//配置文件
	
	std::string		sHost;//服务器IP
	bool			bDaemonize;//是否守护进行
	bool			bRouter;//是否router server
	bool			bEventConnect;//新连接是否通知
	bool			bEventClose;//关闭连接是否通知
	bool			bAcceptLock;
	short			nPort;//服务器端口
	short			nWorkers;//进程数
	int				nServerId;//服务器id
	int				nMaxClients;//最大连接数
	int				nProtocol;//协议
	int				nSendBufferSize;//最大发送缓存区大小
	int				nRecvBufferSize;//最大接受缓冲区大小
	std::string		sLogFile;//日志文件
	int				nLogLevel;//日志级别
	std::string		sRouterHost;//路由服务器ip
	short			nRouterPort;//路由服务器port
	std::string		sScript;//script
	BackendServer	arrBackendServer;//后端服务器
	int				nBackendTimeout;//后端超时时间
	int				nMaxBackendWeights;//后端服务器总权重值			
	
	//fastcgi协议配置
	std::string		sFastcgiRoot;
	std::string		sFastcgiFile;
	FastcgiParams	arFastcgiParams;
	
	//单例?
	static Master*	pInstance;
};
NS_END